package com.icepeach.icepeachhomeback.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.icepeach.icepeachhomeback.entity.User;
import com.icepeach.icepeachhomeback.util.DateUtil;
import com.icepeach.icepeachhomeback.util.TokenUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        this.setFieldValByName("createTime", DateUtil.getFullNowDateTime(), metaObject);
        this.setFieldValByName("updateTime", DateUtil.getFullNowDateTime(), metaObject);
        User currrentUser = TokenUtils.getCurrrentUser();
        if (Objects.nonNull(currrentUser)) {
            this.setFieldValByName("createUser", currrentUser.getNickname(), metaObject);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.setFieldValByName("updateTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()), metaObject);

    }
}
